package ca.etsmtl.log730.projet2.connectors.client.tcpip;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import ca.etsmtl.log730.projet2.connectors.AbstractAdapter;
import ca.etsmtl.log730.projet2.connectors.client.ClientSetup;

public class TcpIpClientSetup implements ClientSetup {

	private int port = 1234;
	private String hostname = "127.0.0.1";
	
	public int getPort() {
		return port;
	}
	public void setPort(int p) {
		this.port = p;
	}
	public String getHostname() {
		return hostname;
	}
	public void setHostname(String s) {
		hostname = s;
	}
	private NioSocketConnector connector;
	@Override
	public void open() {
	    connector = new NioSocketConnector();

	    // Configure the service.
	    connector.setConnectTimeoutMillis(5000);
	       connector.getFilterChain().addLast("codec",
	                                         new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
	    connector.getFilterChain().addLast("logger", new LoggingFilter());
	    connector.setHandler((IoHandler) getAdapter());

	    IoSession session;
//	    for (;;) {
	        try {
	        	InetSocketAddress is = new InetSocketAddress(hostname, port);
				ConnectFuture future = connector.connect(is);
	            System.out.println("CONNECTED!");
				future.awaitUninterruptibly();
	            session = future.getSession();
//	            break;
	        } catch (Exception e) {
	            System.err.println("Failed to connect.");
	            e.printStackTrace();
	            try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
	        }
//	    }

	    // wait until the summation is done
//	    session.getCloseFuture().awaitUninterruptibly();
//	    connector.dispose();
	}
	@Override
	public void close() {
		connector.dispose();
	}
	private AbstractAdapter adapter;
	@Override
	public void setAdapter(AbstractAdapter aa) {
		adapter = aa;
	}
	@Override
	public AbstractAdapter getAdapter() {
		return adapter;
	}
}
